/**   
 * @{#} HashMatchBy.java Create on 2013-8-6 上午8:49:38   
 *   
 * Copyright (c) 2012 by Baidu.   
 */
package objtable.algm.extend;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.google.common.base.Charsets;
import com.google.common.io.Files;

import objtable.algm.Algm2Row;
import objtable.core.ScriptEnv;
import objtable.struct.Row;

/**
 * @author <a href="mailto:zhangbo07@baidu.com">zhangbo07</a>
 * @version 1.0
 */

public class HashMatchBy implements Algm2Row {
	private String condition;
	private String express;
	public static Pattern P_MATCHBY = Pattern
			.compile("\\s*([a|b].\\w*)\\s*==\\s*([a|b].\\w*)\\s*");
	List<String> al = new ArrayList<String>();
	List<String> bl = new ArrayList<String>();

	/**
	 * @param simpleExpress
	 *            会用if语句进行包装
	 * @param complexExpress
	 * @param oneToOneCheck
	 *            是否是1对1映射的检查，如果不满足1对1映射的需求，则向外报错
	 */
	public HashMatchBy(String simpleExpress, String complexExpress) {
		this.condition = simpleExpress;
		parseCondition();
		this.express = complexExpress;
	}

	private void parseCondition() {
		Matcher m = P_MATCHBY.matcher(condition);
		while (m.find()) {
			String t = m.group(1);
			String t1 = m.group(2);
			if (t.startsWith("a.")) {
				al.add(t.substring(2));
			} else {
				bl.add(t.substring(2));
			}

			if (t1.startsWith("a.")) {
				al.add(t.substring(2));
			} else {
				bl.add(t.substring(2));
			}
		}
	}

	private String wrapExpress() {
		String code = "";
		try {
			code = Files.toString(new File("./codescript/hashmatchby.groovy"),
					Charsets.UTF_8);
		} catch (IOException e) {
			e.printStackTrace();
		}
		code = code.replaceAll("#akey", genKeyStr("a.", al));
		code = code.replaceAll("#bkey", genKeyStr("b.", bl));
		code = code.replaceAll("#cond", condition);
		code = code.replaceAll("#exp", express);
		return code;
	}

	public String genKeyStr(String head, List<String> fields) {
		String key = "\"\"";
		for (String f : fields) {
			key += ("+" + head + f + "+\"" + Row.SPLIT_CHAR + "\"");
		}
		return key.substring(0, key.length() - 4);
	}

	public void execute(List<? extends Row> rowa, List<? extends Row> rowb) {
		HashMap<String, Object> hm = ScriptEnv.cloneComputeObj();
		hm.put("a_objs", rowa);
		hm.put("b_objs", rowb);

		ScriptEnv.execute(wrapExpress(), hm);
	}
}
